package com.lizhi.rpc.handler;

import com.lizhi.common.yun.entity.RpcClientPOJO;
import com.lizhi.common.yun.entity.RpcServicePOJO;
import com.lizhi.common.yun.entity.UpDataPOJO;
import com.lizhi.common.yun.enums.HeartBeartEnum;
import com.lizhi.utils.DateUtils;
import com.lizhi.utils.StringUtils;
import com.lizhi.utils.json.SamJsonUtil;
import com.lizhi.yun.db.sfrobot.entity.Doctor;
import com.lizhi.yun.db.sfrobot.entity.Patient;
import com.lizhi.yun.db.sfrobot.repository.DoctorRepo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.Example;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * @Author: lizhi
 * @Description:
 * @Date: create in 2020/12/16 10:20
 */
@Slf4j
@Service
public class RecvDoctorHandler {

    @Resource
    private DoctorRepo doctorRepo;

    public String recvDoctor(String json){
        UpDataPOJO upClientPOJO = SamJsonUtil.toObject(json, UpDataPOJO.class);
        RpcClientPOJO rpcClientPOJO = upClientPOJO.getRpcClientPOJO();

        RpcServicePOJO rpcServicePOJO = new RpcServicePOJO();
        rpcServicePOJO.setSystemType(rpcClientPOJO.getSystemType());
        rpcServicePOJO.setOrganId(rpcClientPOJO.getOrganId());
        rpcServicePOJO.setBkOrganId(rpcClientPOJO.getBkOrganId());
        if (StringUtils.isEmpty(rpcClientPOJO)){
            rpcServicePOJO.setErrorCode(HeartBeartEnum.HEART_BEART_000001.getEnValue());
            rpcServicePOJO.setMessage(HeartBeartEnum.HEART_BEART_000001.getEnName());
            return SamJsonUtil.toJson(rpcServicePOJO);
        }

        /*上传的数据信息信息*/
        Doctor doctor = SamJsonUtil.toObject(upClientPOJO.getData(), Doctor.class);
        if (StringUtils.isEmpty(doctor)){
            rpcServicePOJO.setErrorCode(HeartBeartEnum.HEART_BEART_000002.getEnValue());
            rpcServicePOJO.setMessage(HeartBeartEnum.HEART_BEART_000002.getEnName());
            return SamJsonUtil.toJson(rpcServicePOJO);
        }

        Doctor example = new Doctor();
        example.setId(doctor.id);
        example.setHospitalId(rpcClientPOJO.getOrganId());
        example.setHospitalSystemId(rpcClientPOJO.getBkOrganId());
        Doctor recordFromDb = doctorRepo.findOne(Example.of(example)).orElse(null);
        if (StringUtils.isEmpty(recordFromDb)){
            doctor.setLid(StringUtils.newId());
        } else {
            doctor.setLid(recordFromDb.lid);
        }
        /*将医院编号和设备编号放进来，以判断是哪个设备传输的*/
        doctor.setCreateTime(DateUtils.getNowDate());
        doctor.setHospitalId(rpcClientPOJO.getOrganId());
        doctor.setHospitalSystemId(rpcClientPOJO.getBkOrganId());
        log.info("上传的数据信息是doctor:{}", doctor);
        doctorRepo.save(doctor);
        rpcServicePOJO.setErrorCode(HeartBeartEnum.HEART_BEART_000000.getEnValue());
        rpcServicePOJO.setMessage(HeartBeartEnum.HEART_BEART_000000.getEnName());
        return SamJsonUtil.toJson(rpcServicePOJO);
    }
}
